package com.android.tnovoselec.schedule.async;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.util.Log;

import com.android.tnovoselec.schedule.dto.ItemDto;
import com.android.tnovoselec.schedule.dto.ItemsResultHolder;
import com.j256.ormlite.dao.Dao;

public class GetAllItemsAsync extends AsyncTask<Void, Void, List<ItemDto>> {
	
	public interface ItemsFetchedListener{
		void onItemsFetched();
	}
	
	public static String TAG = GetAllItemsAsync.class.getSimpleName();

	private Dao<ItemDto, String> scheduleDao = null;
	private ItemsFetchedListener listener;

	public GetAllItemsAsync(Dao<ItemDto, String> scheduleDao) {
		super();
		this.scheduleDao = scheduleDao;
	}

	@Override
	protected List<ItemDto> doInBackground(Void... params) {
		List<ItemDto> items = new ArrayList<ItemDto>();
		try {
			items = scheduleDao.queryForAll();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
		return items;
	}

	@Override
	protected void onPostExecute(List<ItemDto> result) {
		ItemsResultHolder.clear();

		for (ItemDto item : result) {
			if (ItemsResultHolder.getItemsByDay(item.getDay()) == null) {
				ItemsResultHolder.init( Integer.valueOf(item.getDay()), new ArrayList<ItemDto>());
			}
			ItemsResultHolder.addItemByDay(item.getDay(), item);
		}
		if (listener != null){
			listener.onItemsFetched();
		}
	}

	public void setListener(ItemsFetchedListener listener) {
		this.listener = listener;
	}
	
}
